package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Controller
public class ArticleController {
    private static File articleDir;

    static {
        articleDir = new File("./articles");
        if (!articleDir.exists()) {
            articleDir.mkdirs();
        }
    }

    @RequestMapping("/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response) {
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        if (title == null || title.trim().isEmpty() ||
                author == null || author.trim().isEmpty() ||
                content == null || content.trim().isEmpty()) {
            response.sendRedirect("/article_fail.html");
            return;
        }
        File file = new File(articleDir, title + ".obj");
        if (file.exists()) {
            response.sendRedirect("/article_fail.html");
            return;
        }
        Article article = new Article(title, author, content);
        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            oos.writeObject(article);
            response.sendRedirect("/article_success.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
